package com.pyb.controller;

import com.pyb.utils.FileScanner;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;
@Controller
public class DoUpload {
    private static final String UPLOAD_DIR = "uploads"; // 文件上传目录
    @RequestMapping(value = "/doUpload", method = RequestMethod.POST)
    public ModelAndView handleFileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("uploadResult");
        try {
            if (file.isEmpty()) {
                modelAndView.addObject("message", "Failed to upload. File is empty.");
            } else {
                // 获取应用上下文路径
                String appContextPath = request.getServletContext().getRealPath("/");
                System.out.println(appContextPath);
                // 构建上传文件的存储路径
                Path uploadDirPath = Paths.get(appContextPath, UPLOAD_DIR);
                // 确保上传目录存在
                Files.createDirectories(uploadDirPath);
                // 获取原始文件名并生成唯一的文件名
                String originalFilename = file.getOriginalFilename();
                if (originalFilename == null || originalFilename.isEmpty()) {
                    throw new IOException("Invalid file name");
                }

                String fileExtension = getFileExtension(originalFilename);
                String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

                // 构建完整的目标文件路径
                Path targetLocation = uploadDirPath.resolve(uniqueFileName);
                System.out.println(targetLocation);

                // 将文件保存到目标位置
                file.transferTo(targetLocation);
                List<String> fileList = FileScanner.listFiles(uploadDirPath.toString());
                // 创建ModelAndView对象用于返回视图和数据
                modelAndView.addObject("fileList", fileList);
                modelAndView.addObject("message", "You successfully uploaded " + originalFilename);
                modelAndView.addObject("filePath", targetLocation.toString()); // 传递文件路径给视图
            }
        } catch (IOException e) {
            modelAndView.addObject("message", "Failed to upload. Error: " + e.getMessage());
        }

        return modelAndView;
    }
    private String getFileExtension(String fileName) {
        int lastIndex = fileName.lastIndexOf('.');
        return (lastIndex != -1) ? fileName.substring(lastIndex) : "";
    }
}